﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DTO;
using System.Data.SqlClient;
using System.Data;

namespace DAO
{
    public class PhieuNhapKhoDAO
    {
        public List<PhieuNhapKhoDTO> LayDanhSachPhieuNhapKho()
        {
            List<PhieuNhapKhoDTO> listPNK = new List<PhieuNhapKhoDTO>();
            SqlConnection conn = null;
            SqlDataReader reader = null;
            try
            {
                String sql = "SELECT a.*, b.TenNV from PhieuNhapKho a, NhanVien b WHERE a.MaNV = b.MaNV";

                conn = DataProvider.ConnectDB();
                SqlCommand cm = new SqlCommand(sql, conn);
                reader = cm.ExecuteReader();
                while (reader.Read())
                {
                    PhieuNhapKhoDTO pnkDTO = new PhieuNhapKhoDTO();
                    pnkDTO.MaPhieuNK = reader.GetInt32(0);
                    pnkDTO.NgayLap = reader.GetDateTime(1);
                    pnkDTO.MaNV = reader.GetInt32(2);
                    pnkDTO.MaDDH = reader.GetInt32(3);
                    pnkDTO.TongTien = Convert.ToDouble(reader.GetDecimal(4));
                    pnkDTO.TenNV = reader.GetString(5);
                    listPNK.Add(pnkDTO);
                }
            }
            catch (Exception ex)
            { String e = ex.ToString(); }
            finally
            { conn.Close(); }
            return listPNK;
        }

        public int ThemPhieuNhapKho(PhieuNhapKhoDTO pdcDTO)
        {
            int ID = -1;
            SqlConnection conn = null;
            try
            {
                conn = DataProvider.ConnectDB();
                String sql = "INSERT INTO PhieuNhapKho(NgayLap, MaNV, MaDDH, TongTien) ";
                sql += "VALUES(@NgayLap, @MaNV, @MaDDH, @TongTien)";
                SqlCommand cmd = conn.CreateCommand();
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = sql;
                SqlParameter para;
                para = cmd.Parameters.Add("@NgayLap", SqlDbType.Date);
                para.Value = pdcDTO.NgayLap;
                para = cmd.Parameters.Add("@MaNV", SqlDbType.Int);
                para.Value = pdcDTO.MaNV;
                para = cmd.Parameters.Add("@MaDDH", SqlDbType.Int);
                para.Value = pdcDTO.MaDDH;
                para = cmd.Parameters.Add("@TongTien", SqlDbType.Decimal);
                para.Value = pdcDTO.TongTien;

                cmd.ExecuteNonQuery();

                String strSQL = "Select @@IDENTITY";
                cmd = new SqlCommand(strSQL, conn);
                ID = Convert.ToInt32(cmd.ExecuteScalar());
                conn.Close();
            }
            catch (Exception ex)
            {
                String e = ex.ToString(); 
            }
            return ID;
        }
    }
}
